<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html xmlns:v="urn:schemas-microsoft-com:vml">
	<head>
		<title>交办详情</title>
<%--		<?import namespace="v" implementation="#default#VML" ?>--%>
		<link rel="stylesheet" type="text/css" href="/css/workflow/flowtype/default.css"/>
		<link rel="stylesheet" href="/lib/layui/layui/css/layui.css">
		<script type="text/javascript" src="/js/jquery/jquery-1.9.1.js"></script>
		<script type="text/javascript" src="/js/base/base.js"></script>
		<script src="/js/jquery/jquery.cookie.js"></script>
		<script src="/lib/layui/layui/layui.js"></script>
		
		<style>
			.srcCla {
				position: relative;
				padding: 20px 10px;
			}
			
			.srcCla .assignment_head {
				font-size: 20px;
				width: 96%;
				text-align: center;
				margin: 0 auto;
				line-height: 50px;
				color: #2F5C8F;
				font-weight: bold;
			}
			
			.srcCla table td {
				vertical-align: middle;
			}
		
		</style>
	</head>
	<body>
		<div class="srcCla">
			<div class="assignment_head">
				交办详情
			</div>
			<table id="assignmenttable" lay-filter="assignmenttable"></table>
		</div>
		
		<%--工作办理--%>
		<div id="workDone" style="display: none;padding: 10px 30px 10px 0;">
			<form class="layui-form">
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label" style="margin-top:30px;">办理汇报：</label>
					<div class="layui-input-block">
						<textarea id="neirong1" name="desc" style="resize: none;" class="layui-textarea"></textarea>
					</div>
				</div>
				<%-- 办理附件 TODO --%>
				<%--            <div class="layui-upload" style="height: auto">--%>
				<%--                <div id="demo3" style="padding-left: 110px;"></div>--%>
				<%--                <label class="layui-form-label" style="margin-left: -22px;">附件：</label>--%>
				
				<%--                <button type="button" class="layui-btn layui-btn-primary " id="test4" style="border: 0px;color:#3870d7;margin-left:5px;"><img src="/img/icon_uplod.png" style="margin-right:5px;"><i style="display: none" class="layui-icon"></i>附件上传</button>--%>
				<%--            </div>--%>
				<div class="layui-form-item">
					<label class="layui-form-label" style="margin-left: -22px;">提醒：</label>
					<div class="layui-input-block">
						<input type="checkbox" name="smstype" value="5" title="发送事务提醒消息" lay-skin="primary" checked>
						<input type="checkbox" name="smstype" value="6" title="使用手机短信提醒" lay-skin="primary">
					</div>
				</div>
			</form>
		
		</div>
		
		<%--工作交办--%>
		<div id="work" style="display: none; padding: 10px 30px 10px 15px;">
			<form class="layui-form" lay-filter="workForm">
<%--				<div class="layui-form-item layui-form-text">--%>
<%--					<label class="layui-form-label" style="margin-top:30px;">交办内容：</label>--%>
<%--					<div class="layui-input-block">--%>
<%--						<textarea id="neirong" name="desc" style="display: inline-block;width: 600px;resize:none;" placeholder=" "--%>
<%--						          class="layui-textarea"></textarea>--%>
<%--                        <div style="display: inline-block;">--%>
<%--							<a href="javascript:;" id="assignmentSign" style="color: blue; text-decoration: none;">添加常用意见</a>--%>
<%--						</div>--%>
<%--					</div>--%>
<%--				</div>--%>
				<div class="layui-form-item ">
					<label class="layui-form-label">办理人：</label>
					<div class="layui-input-block ">
						<textarea id="chargePerson" user_id="" type="text" required disabled name="title"
						          style="display: inline-block;width: 600px;resize:none;min-height: 50px;"
						          class="layui-textarea"></textarea>
						<div style="display: inline-block;">
							<a href="javascript:;" id="userAdd" style="color: blue; text-decoration: none;">添加</a>
							<a href="javascript:;" id="delUser" style="color: red; text-decoration: none;">清除</a>
						</div>
					</div>
				</div>
				<div class="layui-form-item " style="font-size: 13px">
					<label class="layui-form-label laclass" style="width: 145px;">是否允许填写会签意见：</label>
					<input type="radio" name="opinionType" title="是" checked>
					<input type="radio" name="opinionType" title="否">
				</div>
				<%--    交办附件 TODO        --%>
				<%--            <div class="layui-upload" style="height: auto">--%>
				<%--                <div id="demo2" style="padding-left: 110px;"></div>--%>
				<%--                <label class="layui-form-label">附件：</label>--%>
				<%--                <button type="button" class="layui-btn layui-btn-primary" id="test3" style="border: 0px;color:#3870d7;padding: 0;"><img src="/img/icon_uplod.png" style="margin-right: 5px;"><i style="display: none" class="layui-icon"></i>附件上传</button>--%>
				<%--            </div>--%>
				<div class="layui-form-item">
					<label class="layui-form-label">提醒：</label>
					<div class="layui-input-block">
						<input type="checkbox" name="smstype" value="5" title="发送事务提醒消息" lay-skin="primary" checked>
						<input type="checkbox" name="smstype" value="6" title="使用手机短信提醒" lay-skin="primary">
					</div>
				</div>
			</form>
		</div>
		
		<!-- 交办详情 -->
		<script type="text/html" id="assignmentBar">
			{{#  if(d.handleStatus != 2 && d.handleUser == userId){ }}
			<a class="layui-btn layui-btn-xs" lay-event="1">办理</a>
			<a class="layui-btn layui-btn-xs" lay-event="2">交办</a>
			{{#  } }}
		</script>
		
		<script>
            var user_id = '';
            var globalData = {}
            var querySearch = decodeURI(location.search.split('?')[1]).split('&');

            querySearch.forEach(function (query) {
                var key = query.split('=')[0],
                    value = query.split('=')[1];
                globalData[key] = value;
            });

            var userId = $.cookie('userId');
            
            // 获取当前哟用户信息 移动端获取不到cookie
            $.ajax({
	            url: '/getLoginUser',
	            type: 'GET',
	            dataType: 'json',
	            async: false,
	            success: function(res){
	                userId = res.object.userId
	            }
            })

            $(function () {
                var heights = (document.documentElement.clientHeight || document.body.clientHeight) - 105;
                $('.srcCla').height(heights);

                var workObj = {
                    ele: null,
                    workIndex: null,
                    workOpen: false
                }

                layui.use(['form', 'table', 'layer'], function () {
                    var table = layui.table,
                        layer = layui.layer,
                        form = layui.form;

                    form.render();

                    var tableIns = null;
                    initAssignmentTable();

                    //监听-交办详情-表格-工具条
                    table.on('tool(assignmenttable)', function (obj) {
                        workObj.ele = $(this);
                        var tData = obj.data;
                        var layEvent = obj.event;
                        console.log(obj)

                        if (layEvent === '1') { // 工作办理
                            layer.open({
                                title: '工作办理',
                                type: 1,
                                area: ['100%', '70%'],
                                content: $('#workDone'),
                                btn: ['确定', '取消'],
                                success: function () {
                                    $('input[name="smstype"]', $('#workDone')).eq(0).prop("checked", true);
                                    $('input[name="smstype"]', $('#workDone')).eq(1).prop("checked", false);

                                    form.render();
                                }
                                , yes: function () {

                                    var tipMsg = '您有新的公文需要办理，流水号：' + globalData.runId + '，工作名称/文号：' + globalData.runName,
                                        smsType = '',
                                        attachmentId = '',
                                        attachmentName = '';

                                    var $smsType = $('input[name="smstype"]:checkbox:checked', $('#workDone'));
                                    $smsType.each(function () {
                                        smsType += $(this).val() + ',';
                                    });
                                    // var $attachments = $('#demo3').find('input[type="hidden"]');
                                    // $attachments.each(function(){
                                    //     attachmentId += $(this).val();
                                    //     attachmentName += $(this).data('attachname') + ',';
                                    // });

                                    var data = {
                                        taskFeedback: $("#neirong1").val(),
                                        flowId: globalData.flowId,
                                        smsType: smsType,
                                        smsContent: tipMsg,
                                        runId: globalData.runId,
                                        prcsId: globalData.prcsId,
                                        currentPrcsId: globalData.currentPrcsId,
                                        fdAttachmentName: attachmentName,
                                        fdAttachmentID: attachmentId,
                                        assignId: tData.assignId,
                                        id: globalData.id,
                                        tableName: globalData.tableName,
                                        tabId: globalData.tabId,
                                        runName: globalData.runName,
                                    }

                                    $.post('/flowAssign/update', data, function (res) {
                                        if (res.flag) {
                                            tableIns.reload();
                                            layer.closeAll();
                                            $('#neirong1').val('');
                                            // $('#demo3').empty();
                                        }
                                    });
                                },
                                btn2: function () {
                                    layer.closeAll();
                                    $('#neirong1').val('');
                                    // $('#demo3').empty();
                                },
                                cancel: function () {
                                    layer.closeAll();
                                    $('#neirong1').val('');
                                    // $('#demo3').empty();
                                }
                            });
                        } else if (layEvent === '2') { // 工作交办
                            workObj.workIndex = layer.open({
                                title: '工作交办',
                                id: 'workModal',
                                type: 1,
                                area: ['100%', '70%'],
                                content: $('#work'),
                                btn: ['确定', '取消'],
                                success: function () {

                                    if (!workObj.workOpen) {
                                        if (globalData.feedback == 0) {
                                            $('input[name="opinionType"]', $('#work')).eq(0).prop("checked", true);
                                            $('input[name="opinionType"]', $('#work')).eq(1).prop("checked", false).attr('disabled', false);
                                        } else if (globalData.feedback == 1) {
                                            $('input[name="opinionType"]', $('#work')).eq(0).prop("checked", false);
                                            $('input[name="opinionType"]', $('#work')).eq(1).prop("checked", true);
                                        }

                                        $('input[name="smstype"]', $('#work')).eq(0).prop("checked", true);
                                        $('input[name="smstype"]', $('#work')).eq(1).prop("checked", false);

                                        form.render();
                                        workObj.workOpen = true;
                                    }

                                }
                                , yes: function () {

                                    var tipMsg = '您有新的公文需要办理，流水号：' + globalData.runId + '，工作名称/文号：' + globalData.runName,
                                        smsType1 = '',
                                        attachmentId = '',
                                        attachmentName = '',
                                        assignTask = '',// $("#neirong").val().trim(),
                                        jingbanUser = $('#chargePerson').attr('user_id') || '';
                                    
                                    // if (assignTask == '') {
                                    //     layer.msg('请选择填写交办内容！', {icon: 2});
                                    //     return false;
                                    // }
        
                                    if (jingbanUser == '') {
                                        layer.msg('请选择办理人！', {icon: 2});
                                        return false;
                                    }

                                    var $smsType1 = $('input[name="smstype"]:checkbox:checked', $('#work'));
                                    $smsType1.each(function () {
                                        smsType1 += $(this).val() + ',';
                                    });

                                    // var $attachments = $('#demo2').find('input[type="hidden"]');
                                    // $attachments.each(function(){
                                    //     attachmentId += $(this).val();
                                    //     attachmentName += $(this).data('attachname') + ',';
                                    // });

                                    var data = {
                                        assignTask: assignTask,
                                        flowId: globalData.flowId,
                                        runId: globalData.runId,
                                        thisrunName: globalData.thisrunName,
                                        tableName: globalData.tableName,
                                        jingbanUser: jingbanUser,
                                        viewUser: globalData.viewUser,
                                        prcsflag: 1,
                                        prcsId: globalData.prcsId,
                                        currentPrcsId: globalData.prcsId,
                                        flowPrcs: globalData.flowPrcs,
                                        signYn: globalData.feedback,
                                        prcsName: globalData.prcsName,
                                        attachmentId: attachmentId,
                                        attachmentName: attachmentName,
                                        smsType: smsType1,
                                        smsContent: tipMsg,
                                        assignId: tData.assignId
                                    }

                                    $.post('/flowAssign/saveWork2', data, function (res) {
                                        if (res.flag) {
                                            tableIns.reload();
                                            layer.closeAll();
                                            // 清空内容
                                            $('#neirong').val('');
                                            // 清空交办人
                                            $('#chargePerson').get(0).setAttribute('user_id', '');
                                            $('#chargePerson').val('');
                                            // 清空附件信息
                                            // $('#demo2').empty();
                                            workObj.workOpen = false;
                                        }
                                    });
                                },
                                btn2: function () {
                                    layer.closeAll();
                                    // 清空内容
                                    $('#neirong').val('');
                                    // 清空交办人
                                    $('#chargePerson').get(0).setAttribute('user_id', '');
                                    $('#chargePerson').val('');
                                    // 清空附件信息
                                    // $('#demo2').empty();
                                    workObj.workOpen = false
                                },
                                cancel: function () {
                                    layer.closeAll();
                                    // 清空内容
                                    $('#neirong').val('');
                                    // 清空交办人
                                    $('#chargePerson').get(0).setAttribute('user_id', '');
                                    $('#chargePerson').val('');
                                    // 清空附件信息
                                    // $('#demo2').empty();
                                    workObj.workOpen = false
                                }
                            });
                        }
                    });

                    function initAssignmentTable() {
                        tableIns = table.render({
                            elem: '#assignmenttable'
                            , url: '/flowAssign/query?runId=' + globalData.runId
                            , page: false
                            , cols: [[
                                {
                                    field: 'flowPrcs', align: 'center', title: '步骤', minWidth: 70,
                                    templet: function (d) {
                                        return '第' + d.flowPrcs + '步';
                                    }
                                },
                                {field: 'prcsName', align: 'center', title: '步骤名称', minWidth: 100},
                                {
                                    field: 'assignUserName', align: 'center', title: '交办人', minWidth: 110,
                                    templet: function (d) {
                                        return d.assignUserName + '<input class="parentassignid" type="hidden" value="' + d.parentAssignId + '"/>';
                                    }
                                },
                                {field: 'handleUserName', align: 'center', title: '办理人', minWidth: 110},
                                // {field: 'assignTask', align: 'center', title: '交办任务', minWidth: 100},
                                {
                                    field: 'handleStatus', align: 'center', title: '办理状态', minWidth: 100,
                                    templet: function (d) {
                                        var str = '未接收';
                                        if (d.handleStatus == 1) {
                                            str = '办理中';
                                        } else if (d.handleStatus == 2) {
                                            str = '办结';
                                        }
                                        return str;
                                    }
                                },
                                {field: 'assignTime', align: 'center', title: '交办时间', minWidth: 180},
                                {field: 'handleHour', align: 'center', title: '时限', minWidth: 80},
                                {field: 'receiveTime', align: 'center', title: '任务接收时间', minWidth: 180},
                                {field: 'taskFeedback', align: 'center', title: '办理汇报', minWidth: 160},
                                {fixed: 'right', title: '操作', align: 'center', toolbar: '#assignmentBar', minWidth: 120}
                            ]],
                            done: function (res) {
                                layer.closeAll();
                                if (!res.flag) {
                                    $('#assignmentDetail').hide();
                                    return false;
                                }
                                $('#assignmentDetail').show();
                                $('.divShow').parent().css('height', 'auto');
                                $('.divShow').parent().css('overflow', 'visible');
                                merge(res);
                            }
                            , response: {
                                statusName: 'flag',
                                statusCode: true,
                                dataName: 'object'
                            }
                        });
                    }

                    // 合并单元格方法
                    function merge(res) {
                        var data = res.object;
                        var mergeIndex = 0;//定位需要添加合并属性的行数
                        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
                        var columsName = ['flowPrcs', 'prcsName', 'parentAssignId'];//需要合并的列名称
                        var columsIndex = [0, 1, 2];//需要合并的列索引值

                        var toolArr = $(".layui-table-fixed>.layui-table-body>.layui-table").find("tr");

                        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
                            var trArr = $(".layui-table-main>.layui-table").find("tr");//所有行
                            for (var i = 1; i < data.length; i++) { //这里循环表格当前的数据
                                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                                toolArr.eq(i - 1).css({
                                    height: function () {
                                        return trArr.eq(i - 1).height();
                                    }
                                });
                                if (data[i][columsName[k]] === data[i - 1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                                    if (k == 2 && (data[i]['flowPrcs'] != data[i - 1]['flowPrcs'])) {
                                        mergeIndex = i;
                                        mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                                        continue;
                                    }
                                    mark += 1;
                                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                                        $(this).attr("rowspan", mark);
                                    });
                                    tdCurArr.each(function () {//当前行隐藏
                                        $(this).css("display", "none");
                                    });
                                } else {
                                    mergeIndex = i;
                                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                                }
                            }
                            mergeIndex = 0;
                            mark = 1;
                        }
                    }
    
                    // 工作交办-添加经办人
                    $('#userAdd').on('click', function () {
                        user_id = 'chargePerson';
        
                        layer.open({
                            type: 2,
                            shade: true,
                            area: ['98%', '500px'],
                            content: ['/common/selectUser?0', 'no'],
                            end: function () {
                                var $workModal = $('#layui-layer' + workObj.workIndex);
                                if ($workModal.length == 0) {
                                    $(workObj.ele).trigger('click');
                                }
                            }
                        });
                    });
                    
                    // 工作交办-清空经办人
	                $('#delUser').on('click', function(){
	                    $('#chargePerson').attr('user_id', '')
		                $('#chargePerson').val('')
	                });
    
                    //选择意见
                    $("#assignmentSign").click(function () {
                        var signModalIndex = layer.open({
                            skin: 'sign_modal',
                            title: '选择常用意见',
                            area: ['90%', '50%'],
                            type: 1,
                            content: '<div id="saveRule" >' +
                                    '<ul class="sign_list" style="padding: 5px 10px;"></ul>' +
                                    '</div>'
                            ,
                            btn: ['确定'],
                            btnAlign: 'c',
                            success: function () {
                                $.get('/flowOpinion/selectFlowOpinion', function (res) {
                                    var data = res.object;
                                    if (res.flag) {
                                        if (data.length > 0) {
                                            var str = ''
                                            for (var i = 0; i < data.length; i++) {
                                                str += '<li style="padding: 3px 5px 3px 15px; line-height: 20px;"><input style="margin-right: 5px; vertical-align: middle;" type="radio" name="commonObservation" data-id="' + data[i].opinionId + '" value="' + data[i].opinionContent + '" >' + data[i].opinionContent + '</li>';
                                            }
                                            $('.sign_list').html(str);
                                        }
                                    }
                                });
                            },
                            yes: function () {
                                var oldVal = $("#neirong").val();
                                var opinionContent =  $('input[name="commonObservation"]:checked').val() || '';
        
                                $("#neirong").val(oldVal + opinionContent);
                                
                                layer.close(signModalIndex);
                            }
                        });
                    });
                });
            })
		</script>
	
	</body>
</html xmlns:v="urn:schemas-microsoft-com:vml">
